import {Button, Flex, Spin, message} from "antd";
import {useEffect, useState} from "react";
import {fetchData} from "../apis/api.ts";
import styled from "styled-components"
import TextArea from "antd/es/input/TextArea";
import {CaretRightOutlined, StarOutlined, CommentOutlined, LeftOutlined, InfoCircleOutlined,
    CopyOutlined} from "@ant-design/icons";
import "../styles/app.css";
import "../styles/font.css";
import IconComponent from "./IconComponent.tsx";
import {useNavigate, useParams} from "react-router-dom";

const ContentDiv = styled.div`
    background-color: white;
    text-align: center;
    width: 100%;
    max-width: 1000px;
    margin-top: 12px;
    padding: 20px;
  
    border-radius: 4px;
    
    
`;
const CustomTextArea = styled(TextArea)`
  &.ant-input-textarea-show-count:hover, &.ant-input-textarea-affix-wrapper:focus-within{
    border-color: #7848f1 !important;
    box-shadow: 0 0 0 2px rgba(120, 72, 241, 0.2);
  }
`;

interface AppDataType {
    id: number;
    created: string;
    updated: string;
    category: null | string;
    name: string;
    isPublic: boolean;
    icon: string;
    description: string;
    placeholder: string;
    sort: number;
    submitTitle: string;
    categoryId: number;
    maxlength: number;
    model: string;
    starCount: number;
    allowAddToChat: boolean;
    subTips: string;
    isStar: boolean;
}

export default function APPDialogPage() {
    const navigate = useNavigate();
    const { appid } = useParams<{ appid: string }>();


    const [appData, setAppData] = useState<AppDataType | null>(null);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);

    const [inputIsNull, setInputIsNull] = useState<boolean>(true);
    const [isAnswering, setIsAnswering] = useState<boolean>(false);
    const [answerComplete, setAnswerComplete] = useState<boolean>(false);

    const [responseText, setResponseText] = useState(''); // 存储需要复制的文本

    useEffect(() => {
        const getTemplate = async () => {
            try {
                const appDataRequest = await fetchData('/app/'+appid);
                setAppData(appDataRequest);
            } catch (error) {
                setError("Failed to fetch posts.");
            } finally {
                setLoading(false);
            }
        };

        getTemplate();
    }, []);


    if (loading || appData == null) {
        return <div className="loading">
            <Spin tip="加载中..." size="large">
            </Spin>
        </div>;
    }
    if (error){
        return <div>{error}</div>;
    }

    // 返回助手中心
    const handleBack = (): void => {
        navigate('/');
    };

    // 对话发送
    const handleSend = async () => {
        try {
            setIsAnswering(true);
        } catch (error) {
            console.error(error);
            setIsAnswering(false);
        } finally {
            setIsAnswering(false);
            setAnswerComplete(true);
        }
        console.log();
    };
    // 添加到对话
    const handleAddDialog = (): void => {
        console.log("尝试添加到对话");
    };

    const handleSubscribeApp = (): void => {
        console.log("尝试收藏/取消收藏");
    }

    const handleCopyResponse = (): void => {
        const span = document.getElementById('responseText');
        if (span) {
            setResponseText(span.textContent || span.innerText);
        }

        if (responseText) {
            navigator.clipboard.writeText(responseText).then(() => {
                // 文本复制成功
                message.success('复制成功');
            }).catch((err) => {
                // 文本复制失败
                console.error('复制失败：', err);
            });
        }
    }

    // 页面显示隐藏、禁用启用逻辑
    const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>):void => {
        const inputStr = event.target.value;
        console.log(inputStr);
        setInputIsNull(inputStr === "");
    }

    return <Flex vertical style={{width:"100%", alignItems:"center"}}>
        <ContentDiv>
            <span style = {{display:"inline-block",marginTop:"0",marginBottom:"10px",
                fontWeight:'700',fontSize:'large',
                background:'linear-gradient(315deg, #7848f1, #4f0bff)',
                backgroundClip:'text',color:'transparent'}}>
                {appData.name}
            </span>
            <br></br>
            <span style = {{display:"inline-block",marginTop:"0",marginBottom:"10px",
                fontSize:"x-small", color:"dimgray"}}>
                {appData.description}
            </span>

            <CustomTextArea rows={8}
                            onChange={handleInputChange}
                            placeholder={appData.placeholder+" (Shift+Enter换行)"}
                            count={{
                                show: true,
                                max: 1000
                            }}
                      maxLength={1000}/>

            <div>
                <Button onClick={() => {handleBack();}}
                        style={{color:'dimgray', backgroundColor:"#eceded"}} className={"opButtonDialog"} icon={<LeftOutlined />} />

                <Button onClick={() => {handleSend();}}
                        disabled={inputIsNull || isAnswering}
                        style={{color:'#7848f1', backgroundColor:"#d9cff3"}} className={"opButtonDialog"} icon={<CaretRightOutlined />} >
                    {appData.submitTitle}
                </Button>
                {(appData.allowAddToChat &&
                    <Button onClick={() => {handleAddDialog();}}
                            style={{color:'black', backgroundColor:"#eceded"}} className={"opButtonDialog"} icon={<CommentOutlined />} >
                        添至对话
                    </Button>
                )}
                <Button onClick={() => {handleSubscribeApp();}}
                                 style={{color:'sandybrown', backgroundColor:"#f9e7cc"}} className={"opButtonDialog"} icon={<StarOutlined />}>
                    收藏
                </Button>
            </div>
            <span style={{fontSize:"small", color:"dimgray", display:"inline-block", marginTop:"10px"}}>
                <InfoCircleOutlined /> 消耗： {appData.subTips}
            </span>
        </ContentDiv>

        <ContentDiv>
            { !isAnswering && !answerComplete && <div>
                <div>
                <span style={{fontSize:"xxx-large" ,fontWeight:"900", display:"inline-block", marginTop:"10px"}}>
                    <IconComponent iconName={appData.icon} />
                </span>
                </div>
                <div>
                <span style={{fontWeight:"900", display:"inline-block", marginTop:"10px"}}>
                    等待您的输入
                </span>
                </div>
                <div>
                <span style={{fontSize:"small", color:"dimgray", display:"inline-block", marginTop:"10px"}}>
                    点击「{appData.submitTitle}」按钮开始吧！
                </span>
                </div>
            </div>
            }

            <div>
                {
                    (isAnswering || answerComplete) &&
                    <div style={{textAlign:"start"}}>
                        <span id="responseText" style={{display:"inline-block", marginTop:"10px"}}> 你好，有什么可以帮助您的吗？ </span>
                    </div>
                }
                {
                    answerComplete &&
                    <div>
                        <Button onClick={() => {handleCopyResponse();}}
                                style={{color:'#7848f1', backgroundColor:"#d9cff3"}} className={"opButtonDialog"} icon={<CopyOutlined />}>
                            复制结果
                        </Button>
                    </div>

                }
            </div>
        </ContentDiv>
    </Flex>
}